package xiaojian.toolkit.jmdns;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.HashMap;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXServiceURL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.util.ExceptionUtils;

public class ConnectorServerPublisher {
	private static final Logger LOG = LoggerFactory
			.getLogger(ConnectorServerPublisher.class);
	private static final String JMXSRV_TYPE = "_jmxsrv._tcp.local.";
	private final JMXConnectorServer _connectorServer;
	private JmDNS _jmdns;

	public ConnectorServerPublisher(JmDNS jmdns,
			JMXConnectorServer connectorServer) {
		this._jmdns = jmdns;
		this._connectorServer = connectorServer;
		if ((this._jmdns != null) && (this._connectorServer != null)) {
			try {
				init();
			} catch (IOException e) {
				LOG.warn("exception when init, detail: {}",
						ExceptionUtils.exception2detail(e));
			}
		} else {
			LOG.warn(
					"ConnectorServerPublisher disabled bcs jmdns or connectorServer is null. detail: jmdns {}, connectorServer {}",
					this._jmdns, this._connectorServer);
		}
	}

	private void init() throws IOException {
		if (this._connectorServer.getAddress() != null) {
			HashMap<String, String> values = new HashMap();
			values.put("jmxurl", this._connectorServer.getAddress().toString());

			ServiceInfo jmxservice = ServiceInfo.create("_jmxsrv._tcp.local.",
					genName(), 0, 0, 0, values);
			if (LOG.isDebugEnabled()) {
				LOG.debug("create ServiceInfo {} for connectorServer {}",
						jmxservice, this._connectorServer);
			}
			this._jmdns.registerService(jmxservice);
			if (LOG.isDebugEnabled()) {
				LOG.debug("register ServiceInfo {} succeed", jmxservice);
			}
		} else {
			LOG.warn(
					"ConnectorServerPublisher disabled bcs ConnectorServer {}'s address is null",
					this._connectorServer);
		}
	}

	public void stop() {
		this._jmdns.unregisterAllServices();
		try {
			this._jmdns.close();
		} catch (IOException e) {
			LOG.warn("exception when stop, detail: {}",
					ExceptionUtils.exception2detail(e));
		}
	}

	private String genName() {
		return ManagementFactory.getRuntimeMXBean().getName();
	}
}
